﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using WebRole1.DataService;
using System.Data.Objects;

namespace WebRole1.Config
{
   public partial class Location : System.Web.UI.Page
   {
      static DateTime PersistCookie = DateTime.Now.AddYears(10);
      const string LoginCookie = "webauthtoken";

      protected void Page_Load(object sender, EventArgs e)
      {
         if (!Page.IsPostBack)
         {
            FillPlaceholder();

            //EntityDataSource1.Where = "";
            HttpCookie lastPageCookie = new HttpCookie("LastPage");
            lastPageCookie.Value = "Config/Location.aspx";
            lastPageCookie.Expires = PersistCookie;
            Response.Cookies.Add(lastPageCookie);
         }
      }

      private void FillPlaceholder()
      {
         using (LocationsDBEntities locEntities = new LocationsDBEntities())
         {
            string userId = Utils.GetUserFromCookie();

            if (!string.IsNullOrEmpty(userId))
            {
               UserTbl user = Utils.GetCurrentUser(locEntities, userId);
               user.Location.Load();

               PlaceHolderLocations.Controls.Add(new LiteralControl("<p>Modify my locations:</p><ul>"));

               foreach (DataService.Location loc in user.Location.OrderBy(f => f.Name))
               {
                  string linkControl = String.Format("<li><a href='#' onclick=\"ModifyLoc({0});\">{1} ({2})</a> </li>\n",
                           loc.LocationID, loc.Name, loc.Descr);
                  PlaceHolderLocations.Controls.Add(new LiteralControl(linkControl));
               }
               PlaceHolderLocations.Controls.Add(new LiteralControl("</ul>"));
            }
            else
            {
               PlaceHolderLocations.Controls.Add(new LiteralControl("Please login use your Windows Live ID.  Only login users can modify the locations that created by the same user."));
            }
         }
      }

      public UserTbl GetCurrentUser(LocationsDBEntities locEntities)
      {
         string userId = "";
         Label mpLabel = (Label)Master.FindControl("LabelCurrentLiveUser");
         if (mpLabel != null)
         {
            userId = mpLabel.Text;
         }

         return Utils.GetCurrentUser(locEntities, userId);
      }

      protected void ButtonDelete_Click(object sender, EventArgs e)
      {
         if (String.IsNullOrEmpty(TextBoxLocationID.Text.Trim()))
         {
            throw new Exception("Must specify a location to delete");
         }
         using (LocationsDBEntities locEntities = new LocationsDBEntities())
         {
            int locID=0;
            string existingID = TextBoxLocationID.Text.Trim();
            if (!string.IsNullOrEmpty(existingID))
            {
               locID = Convert.ToInt32(existingID);
            }
            if (locID == 0)
            {
               throw new Exception("locationID ID cannot be 0");
            }

            UserTbl user = GetCurrentUser(locEntities);
            DataService.Location myLoc = null;
            
            myLoc = locEntities.Location.First(f => f.LocationID == locID);

            myLoc.UserTblReference.Load();
            if (myLoc.UserTbl.UserID != user.UserID)
            {
               throw new Exception("Only user published this location can delete it.");
            }

            //remove the category relation first
            myLoc.RelationLocCat.Load();
            foreach (RelationLocCat rel in myLoc.RelationLocCat.ToArray())
            {
               locEntities.DeleteObject(rel);
            }

            myLoc.Comment.Load();
            foreach (Comment cmt in myLoc.Comment.ToArray())
            {
               locEntities.DeleteObject(cmt);
            }
            
            locEntities.DeleteObject(myLoc);
            locEntities.SaveChanges();
         }
         FillPlaceholder();
      }

      protected void ButtonPublish_Click(object sender, EventArgs e)
      {
         using (LocationsDBEntities locEntities = new LocationsDBEntities())
         {
            UserTbl user = GetCurrentUser(locEntities);

            //note, can also use TextBoxCurrentCityId to get the city
            string cityname = TextBoxSearchCity.Text.Trim();
            var city = locEntities.City.First(f => f.SearchName == cityname);

            DataService.Location myLoc = null;
            int locID = 0;

            if (String.IsNullOrEmpty(TextBoxLocationID.Text))
            {
               myLoc = new DataService.Location();
               myLoc.Rating = 0; //initial value always 0, as unrated
            }
            else
            {
               locID = Convert.ToInt32(TextBoxLocationID.Text);
               myLoc = locEntities.Location.First(f => f.LocationID == locID);
               myLoc.UserTblReference.Load();
               if (myLoc.UserTbl.UserID != user.UserID)
               {
                  throw new Exception("Only user published this location can modify it.");
               }
            }

            myLoc.City = city;
            myLoc.UserTbl = user;
            myLoc.CreateDatetime = DateTime.Now.ToUniversalTime();

            myLoc.Name = TextBoxLocationName.Text;
            myLoc.Descr = TextBoxLocationdesc.Text;
            myLoc.Address1 = TextBoxAddress1.Text;
            myLoc.Address2 = TextBoxAddress2.Text;
            myLoc.CreateDatetime = DateTime.Now.ToUniversalTime();
            myLoc.Lat = Convert.ToDecimal(TextBoxLatitude.Text);
            myLoc.Lon = Convert.ToDecimal(TextBoxLongtitude.Text);
            myLoc.Url = TextLocationUrl.Text;
            myLoc.NeedEmailUpdate = CheckBoxEmailNotify.Checked;

            myLoc.UrlLink1 = TextBoxUrlLink1.Text;
            myLoc.UrlLink1Mark = TextBoxUrlLink1Mark.Text;
            myLoc.UrlLink2 = TextBoxUrlLink2.Text;
            myLoc.UrlLink2Mark = TextBoxUrlLink2Mark.Text;
            myLoc.Phone = TextBoxPhone.Text;
            myLoc.ImageUrl = TextBoxImageUrl.Text;

            if (locID == 0)
            {
               locEntities.AddToLocation(myLoc);
            }

            locEntities.SaveChanges();

            if (locID > 0)
            {
               //category relationship exist, remove it first
               myLoc.RelationLocCat.Load();
               foreach (RelationLocCat rel in myLoc.RelationLocCat.ToArray())
               {
                  locEntities.DeleteObject(rel);
               }
               locEntities.SaveChanges();
            }

            //save cateogry/location relationship
            char[] sep = { ',' };
            foreach (string catId in TextBoxCategory.Text.Split(sep, StringSplitOptions.RemoveEmptyEntries))
            {
               int catIdInt = Convert.ToInt32(catId);
               DataService.Category myCat = locEntities.Category.First(f => f.CategoryID == catIdInt);
               RelationLocCat newRel = new RelationLocCat();
               newRel.Location = myLoc;
               newRel.Category = myCat;

               locEntities.AddToRelationLocCat(newRel);
            }
            locEntities.SaveChanges();
         }

         FillPlaceholder();
      }
   }
}
